//
//  XZMyMessageSearchVC.m
//  Teecloud
//
//  Created by PC on 2018/11/12.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZMyMessageSearchVC.h"
#import "XZMyMessageResultVC.h"
#import "XZSearchCell.h"
#import "XZSearchHeadView.h"
#import "XZSearchData.h"
#import "XZNotData.h"
#import "XZSearchBar.h"
@interface XZMyMessageSearchVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>
@property (nonatomic, strong) XZSearchData *model;
@property (nonatomic, strong) XZSearchBar *searchBar;
@property (nonatomic, strong) XZNotData *noDataView;
@property (nonatomic, strong) UICollectionView *collectionView;
@end
#define HEADVIEW @"HEADVIEW"
#define IDENTIFIER @"XZSearchCell"
@implementation XZMyMessageSearchVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getSearchKey];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"搜索";
    self.view.backgroundColor = [UIColor colorWithHexString:@"CECECE" andAlpha:1.0f];
    [self creatTitleView];
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    XZMyMessageResultVC *myMessageResultVC = [[XZMyMessageResultVC alloc]init];
    myMessageResultVC.key = searchBar.text;
    [self.navigationController pushViewController:myMessageResultVC animated:true];
}
- (void)creatTitleView{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    //设置titleview，不过这个view并不是我们需要的居中的view；
    self.navigationItem.titleView = titleView;
    __weak typeof(self) weakSelf = self;
    //主线程列队一个block， 这样做 可以获取到autolayout布局后的frame，也就是titleview的frame。在viewDidLayoutSubviews中同样可以获取到布局后的坐标
    __block XZSearchBar *searchBar;
    dispatch_async(dispatch_get_main_queue(), ^{
        //要居中view的宽度
        CGFloat width = 240;
        //实际居中的view
        UIView *centerView = [[UIView alloc]init];
        centerView.backgroundColor = kClearColor;
        //设置一个基于window居中的坐标
        centerView.frame = CGRectMake((DEVICE_WIDTH-width)/2, 20+(kIs_iPhoneX?24:0), width, 44);
        //坐标系转换到titleview
        centerView.frame = [weakSelf.view.window convertRect:centerView.frame toView:weakSelf.navigationItem.titleView];
        searchBar = [[XZSearchBar alloc]initWithFrame:CGRectMake(0, 10, 240, 30)];
        searchBar.delegate = self;
        searchBar.placeholder = @"输入关键字";
        searchBar.tintColor = kBlueColor;
        [centerView addSubview:searchBar];
        self.searchBar = searchBar;
        //centerview添加到titleview
        [weakSelf.navigationItem.titleView addSubview:centerView];
    });
}
#pragma mark - GetHistoryKeys
- (void)getSearchKey{
    NSDictionary *dict= @{
                          @"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"searchFrom":@(2)
                          };
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetSearchKey&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSDictionary *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                XZSearchData *model = [XZSearchData mj_objectWithKeyValues:dataInfo];
                weakself.model = model;
                if (model.LastSearchKeys.count > 0) {
                    self.noDataView.hidden = YES;
                }else{
                   self.noDataView.hidden = NO;
                }
                [weakself.collectionView reloadData];
            }else{
                self.noDataView.hidden = NO;
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            self.noDataView.hidden = NO;
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}

#pragma mark - UICollectionViewDataSource -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.model.LastSearchKeys.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    XZSearchCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:IDENTIFIER forIndexPath:indexPath];
    cell.contentView.backgroundColor = kWhiteColor;
    NSString *key = self.model.LastSearchKeys[indexPath.row];
    cell.searchKey.text = key;
    cell.searchBlock = ^(NSString * _Nonnull key) {
        XZMyMessageResultVC *searchResultVC = [[XZMyMessageResultVC alloc]init];
        searchResultVC.key =key;
        [weakself.navigationController pushViewController:searchResultVC animated:true];
    };
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        XZSearchHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADVIEW forIndexPath:indexPath];
        headView.headTitleLabel.text = @"历史搜索";
        return headView;
    }
    return nil;
}
#pragma mark - UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (self.model.LastSearchKeys.count > 0) {
        return CGSizeMake(kScreenWidth, 40.f);
    }else{
        return CGSizeMake(kScreenWidth, 0.f);
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(kScreenWidth/2, 40);
}

#pragma mark - Override -
- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout * flayOut = [[UICollectionViewFlowLayout alloc]init];
        flayOut.minimumLineSpacing = 0;
        flayOut.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 120) collectionViewLayout:flayOut];
        _collectionView.backgroundColor = kWhiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        _collectionView.showsVerticalScrollIndicator = false;
        _collectionView.showsHorizontalScrollIndicator = false;
        //cell 头部注册
        [_collectionView registerNib:[UINib nibWithNibName:@"XZSearchCell" bundle:nil] forCellWithReuseIdentifier:IDENTIFIER];
        [_collectionView registerNib:[UINib nibWithNibName:@"XZSearchHeadView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADVIEW];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
- (XZNotData *)noDataView{
    if (!_noDataView) {
        _noDataView = [XZNotData viewFromXib];
        [self.view addSubview:_noDataView];
        kWeakObject(self)
        [_noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
    return _noDataView;
}
@end
